package com.qiaofang.dataprocessing.facade.globalexception.handler;


import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.util.StringUtil;

import com.qiaofang.dataprocessing.stub.constants.DataProcessingResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理器
 * @author Administrator
 *
 */
@ControllerAdvice(basePackages="com.qiaofang.dataprocessing")
public class ExpandBusinessGlobalExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(ExpandBusinessGlobalExceptionHandler.class);

//	   @InitBinder  
//	    public void initBinder(WebDataBinder binder) {  
//		   LOGGER.error("GlobalExceptionHandler 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
//	    }  
	   
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		CommonResponse response = new CommonResponse();
		LOGGER.error("There is exception happening",e);
		if(e instanceof BusinessException){
			response.setResponseCode(((BusinessException) e).getErrorCode());
			response.setResponseMessage(e.getMessage());
			
		}else if (e instanceof MethodArgumentNotValidException){
			response.setResponseCode(DataProcessingResponseCode.RC_PARAMETER_ERROR.getResponseCode());
			response.setResponseMessage(DataProcessingResponseCode.RC_PARAMETER_ERROR.getResponseMessage());
			
		}else{
			response.setResponseCode(DataProcessingResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
			if(StringUtil.isNotBlank(e.getMessage())){
				response.setResponseMessage(e.getMessage());
			}else{
				response.setResponseMessage(DataProcessingResponseCode.RC_EXCEPTION_ERROR.getResponseMessage());
			}
		}
		return response;
	}
}
